package com.hapzxb.thread.lock;

import java.util.Arrays;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Bank {


    private Condition sufficientFunds;

    private Lock bankLock = new ReentrantLock();
    private final double[] accounts;

    public Bank(int n, double initialBalance) {
        accounts = new double[n];
        Arrays.fill(accounts, initialBalance);

        sufficientFunds = bankLock.newCondition();
    }

    public void transfer(int from, int to, double amount) {

        bankLock.lock();
        try {
            while (accounts[from] < amount) {
                sufficientFunds.await();
            }
            System.out.print(Thread.currentThread().getName());

            accounts[from] -= amount;
            System.out.printf(" %10.2f from %d to %d", amount, from, to);

            accounts[to] += amount;

            System.out.printf(" Total Balance: %10.2f%n", getTotalBalance());

            sufficientFunds.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            bankLock.unlock();
        }

    }

    private double getTotalBalance() {

        bankLock.lock();
        try {
            double sum = 0;
            for (double a : accounts) {
                sum += a;
            }
            return sum;
        } finally {
            bankLock.unlock();
        }


    }

    public int site() {
        return accounts.length;
    }
}
